const TransformPages = require('uni-read-pages')
const { webpack } = new TransformPages()

const resolve = (dir) => require('path').join(__dirname, dir)
const merge = require('webpack-merge') // base64
const isProd = process.env.NODE_ENV == 'production'
const pde = require('./src/utils/platform-domain-env')

// console.log('process.argv', process.argv)

const lastArgv = process.argv.pop()

if (/^\-\-env\=/.test(lastArgv)) {
  const env = lastArgv.slice(6)
  const [platform, domain, dev] = env.split('-')
  const url = pde.getUrl(platform, domain, dev)

  // 修改请求url
  process.env.VUE_APP_ENV = env
  process.env.VUE_APP_API_URL = url

  // 修改打包目录
  process.env.UNI_OUTPUT_DIR = `dist/build/${process.env.UNI_PLATFORM}/${env}`
}

if (process.env.NODE_ENV === 'production') {
  const commit = require('./build/commit')

  Object.keys(commit).forEach((key) => {
    process.env['VUE_APP_' + key] = commit[key]
  })
}

console.log('正在请求', process.env.VUE_APP_API_URL)

module.exports = {
  transpileDependencies: ['uview-ui', /[/\\]node_modules[/\\](.+?)?@uni-ui(.*)[/\\]code-plugs/],
  publicPath: isProd ? '/uni-ts/' : '',
  productionSourceMap: false, // 生产打包时不输出map文件，增加打包速度
  css: {
    // requireModuleExtension: true, // 是否开启CSSmodule并保留xxx.module.css后缀
    loaderOptions: {
      less: {
        javascriptEnabled: true,
      },
      scss: {
        prependData: `
          @import "~@/uni.scss";
          @import "~@/styles/vars.scss";
          @import "~@/styles/func.scss";
          @import "~@/styles/mixin.scss";
        `,
      },
    },
  },
  devServer: {
    open: true,
    disableHostCheck: true,
    overlay: {
      warnings: false,
      errors: true,
    },
    proxy: {
      '/api': {
        target: process.env.VUE_APP_API_URL,
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '/api': '',
        },
      },
    },
  },
  chainWebpack: (config) => {
    // 配置相关loader，支持修改，添加和替换相关的loader
    config.resolve.alias.set('@', resolve('src'))

    // base64相关代码
    config.module
      .rule('images')
      .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
      .use('url-loader')
      .loader('url-loader')
      .tap((options) =>
        merge(options, {
          limit: 1,
        })
      )
  },
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      // 为了看打印 先注释
      config.optimization.minimizer[0].options.terserOptions.compress.warnings = false
      config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
      config.optimization.minimizer[0].options.terserOptions.compress.drop_debugger = true
      config.optimization.minimizer[0].options.terserOptions.compress.pure_funcs = ['console.log']
    }
    config.plugins.push(
      new webpack.DefinePlugin({
        ROUTES: webpack.DefinePlugin.runtimeValue(() => {
          const tfPages = new TransformPages({
            includes: ['path', 'name', 'aliasPath'],
          })
          return JSON.stringify(tfPages.routes)
        }, true),
      })
    )

    // if (process.env.UNI_PLATFORM === 'mp-weixin') {
    //   const ComponentPlaceholderPlugin = require('component-placeholder-plugin')
    //   config.plugins.push(new ComponentPlaceholderPlugin())
    // }
  },
}
